<?php
/**
 * (logic) 库存总表（站点）
 */

namespace App\Logic\Inventory;

use App\Models\Basics\SysICountry;
use App\Models\Inventory\InventoryTotalArea;
use App\Models\Product\ProductAmazonSku;
use App\Models\Product\ProductSku;
use Exception;
class SyncInventoryArea{

    /**
     * 同步数据
     * 设定：每天运行
     */
    public static function exe(){

        $productAmazonSku = ProductAmazonSku::query()->select('country_id','psku_id')->distinct()->get();

        $area = [];
        $new = [];
        //先处理数据，将countryId_pSkuId => areaId_pSkuId
        if ($productAmazonSku) {
            foreach($productAmazonSku as $_sku){
                if(!array_key_exists($_sku->country_id, $area)){
                    //area_id
                    $area[$_sku->country_id] = SysICountry::getAreaIdByCountryId($_sku->country_id);
                }
                $value = $area[$_sku->country_id].'_'.$_sku->psku_id;
                if(!in_array($value,$new)){
                    $new[] = $value;
                }
            }
        }

        $_new = $new ? array_unique($new) : [];
        $count = count($_new);
        if($count < 2100){
            report(new Exception("Failed to artisan sync_inventory_area_sku : count(" . $count . ")总数异常",121));
            die(0);
        }

        //原数据
        $oldData = InventoryTotalArea::query()->select('area_id','psku_id')->get()->toArray();
        $_old = [];
        if ($oldData) {
            foreach ($oldData as $key => $val){
                $_old[$key] = implode('_', $val);
            }
        }

        $country = [];
        //需要删除的数据
        $delete = array_diff($_old,$_new);
        foreach($delete as $_delete){
            list($areaId,$pSkuId) = explode('_',$_delete);
            if(!array_key_exists($areaId,$country)){
                $country[$areaId] = SysICountry::getCountryIdsByAreaId($areaId);
            }
            $countryIds = $country[$areaId];
            $count = ProductAmazonSku::query()
                ->where('status', ProductAmazonSku::STATUS_YES)
                ->where('psku_id',$pSkuId)
                ->whereIn('country_id',$countryIds)
                ->count();
            if($count > 0)continue;

            InventoryTotalArea::query()->where(['area_id'=>$areaId, 'psku_id'=>$pSkuId])->delete();
        }

        //需要新增的数据
        $add = array_diff($_new,$_old);
        foreach($add as $_add){
            list($areaId,$pSkuId) = explode('_',$_add);

            $productSku = ProductSku::query()->find($pSkuId);
            if(!$productSku) continue;

            InventoryTotalArea::addInventoryTotalArea($areaId,$pSkuId, $productSku->classify_id);
        }
    }
}
